package com.foreknow.elm.framework;
/**
 * @author 啊滨
 * @date 2023/2/13 11:32
 */

import com.fasterxml.jackson.databind.ObjectMapper;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * http://localhost:8080/elm/Controller类名/Controller方法名
 * 自定义前端控制器 拦截url格式要求： /控制器类名/控制器方法名
 */
@WebServlet("/")
public class DispatcherServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置编码格式
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        //获取客户端的请求，获取到url部分路径
        String path = request.getServletPath();//path="Controller类名/Controller方法名"
        //根据以上的字符串获取到类名以及方法名
        String className = path.substring(1, path.lastIndexOf("/"));//截取字符串
        String methodName = path.substring(path.lastIndexOf("/") + 1);
        PrintWriter out = response.getWriter();
        //通过反射调用Controller类名中的方法名
        try {
            //1.获取Class对象.
            Class clazz = Class.forName("com.foreknow.elm.controller." + className);
            //2.获取方法
            Method method = clazz.getMethod(methodName, new Class[]{HttpServletRequest.class});
            //3.调用方法
            Object controller = clazz.newInstance();//创建controller
            Object result = method.invoke(controller, new Object[]{request});
            //4.将结果result要以json格式的字符串返回给前端显示 转换工具jackson-core-2.11.0.jar
            ObjectMapper objectMapper=new ObjectMapper();
            out.print(objectMapper.writeValueAsString(result));

        } catch (ClassNotFoundException | NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
        }
}
